<template>
	<div class="container" style="margin-top: 40px">
		<div v-if="!isEmpty">
			<h3>加入购物车</h3>
			<table class="table table-bordered table-hover">
				<thead>
					<tr>
						<th>序号</th>
						<th>商品名称</th>
						<th>商品单价</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="(list, index) in lists" :key="index">
						<td>{{ index + 1 }}</td>
						<td>{{ list.gname }}</td>
						<td>{{ list.gprice }}</td>
						<td @click="del(index)"><i class="icon icon-trash"></i></td>
					</tr>
				</tbody>
			</table>
			<div style="color: red; font-weight: bold">总价：￥{{ total }}</div>
			<div>
				<button class="btn btn-primary" @click="buyThem">购买</button>
			</div>
		</div>
		<div v-else>
			<img src="../assets/images/提莫.jpg" alt="">
			<h2>购物车里空空如也,请选择商品加入购物车XD</h2>
		</div>
	</div>
</template>

<script>
	export default {
		name: "shoppingCart",
		components: {},
		data() {
			return {
				lists: this.$store.state.shoppingCar
			};
		},
		methods: {
			del(index) {
				this.lists.splice(index, 1);
			},
			buyThem() {
				const config = {
					method: 'post',
					url: 'http://localhost:8080/json/order/addOrder',
					data: {
						uid: this.$store.state.user.uid,
						gid: this.goods
					}
				}
				
				this.$axios(config).then(result => {
					if (result.data == true) {
						this.$message({
							message: '购买成功!',
							type: 'success'
						});
					} else {
						this.$message.error('因未知错误，购买失败~');
					}

				})
			}
		},
		computed: {
			total() {
				var total = 0;
				for (var i = 0; i < this.lists.length; i++) {
					total += this.lists[i].gprice;
				}
				return total;
			},
			goods() {
				var goods = [];
				for (var i = 0; i < this.lists.length; i++) {
					goods.push(this.lists[i].gid);
				}
				return goods;
			},
			isEmpty (){
				var len= this.lists.length;
				if(len==0)
					return true
				else 
					return false
			}
		}
	};
</script>
